package com.vic.service;

import com.alibaba.fastjson.JSON;
import com.vic.common.cache.Cache;
import com.vic.common.cache.aop.KeyGenerateType;
import com.vic.common.cache.aop.anno.CacheDelete;
import com.vic.common.cache.aop.anno.CacheGet;
import com.vic.common.cache.aop.anno.CachePut;
import com.vic.common.constant.CacheKey;
import com.vic.common.properties.DbProperties;
import com.vic.common.response.HttpResponse;
import com.vic.common.response.HttpResponseUtil;
import com.vic.common.util.CommonUtil;
import com.vic.entity.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ArticleService {
    private static final int SUB_TEXT_LENGTH = 200;
    @Autowired
    private DbProperties dbProperties;
    @Autowired
    @Qualifier("localCache")
    private Cache<String, Object> localCache;

    @CacheDelete(prefix = CacheKey.LOCAL_ARTICLE_LIST)
    public HttpResponse saveArticle(Article article) {
        article.setId(CommonUtil.generateId());
        long currentTime = System.currentTimeMillis();

        String content = article.getContent();
        String subContent = "";
        if (content.length() < SUB_TEXT_LENGTH) {
            subContent = content;
        } else {
            subContent = content.substring(0, SUB_TEXT_LENGTH);
        }
        article.setSubContent(subContent);

        article.setCreateTime(currentTime);
        article.setUpdateTime(currentTime);

        saveFile(article);
        return HttpResponseUtil.success("文章保持成功", article);
    }

    /**
     * 更新文章，先删除，然后保存
     *
     * @param article
     * @return
     */
    @CacheDelete(prefix = CacheKey.LOCAL_ARTICLE_DETAIL, generateType=KeyGenerateType.ASSIGN_PROPS,value = "article",
            methodProps = "getId",deleteListKey = CacheKey.LOCAL_ARTICLE_LIST)
    public HttpResponse updateArticle(Article article) {
        deleteFile(article.getId());

        long currentTime = System.currentTimeMillis();

        String content = article.getContent();
        String subContent = "";
        if (content.length() < SUB_TEXT_LENGTH) {
            subContent = content;
        } else {
            subContent = content.substring(0, SUB_TEXT_LENGTH);
        }
        article.setSubContent(subContent);

        article.setUpdateTime(currentTime);

        saveFile(article);
        return HttpResponseUtil.success("文章修改成功", article);
    }


    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @CacheDelete(prefix = CacheKey.LOCAL_ARTICLE_DETAIL, value = "id",deleteListKey = CacheKey.LOCAL_ARTICLE_LIST)
    public HttpResponse deleteArticle(Article id) {
        return deleteFile(id.getId());
    }


    @CacheGet(prefix = CacheKey.LOCAL_ARTICLE_DETAIL, value = "id")
    @CachePut(prefix = CacheKey.LOCAL_ARTICLE_DETAIL, value = "id")
    public Article getArticle(String id) {
        return getFile(id);
    }

    @CacheGet(prefix = CacheKey.LOCAL_ARTICLE_LIST)
    @CachePut(prefix = CacheKey.LOCAL_ARTICLE_LIST)
    public List<Article> getArticles() {
        List<Article> list = new ArrayList<>();
        String path = dbProperties.getArticle();
        File[] files = CommonUtil.getDirFiles(path);
        if (Objects.isNull(files)) {
            return list;
        }
        for (File file : files) {
            Article article = getFile(file.getName());
            list.add(article);
        }
        return list;
    }



    /**
     * 获取文章
     *
     * @param id
     * @return
     */
    private Article getFile(String id) {
        String path = dbProperties.getArticle();
        File file = CommonUtil.getFileByFileName(path, id);
        if (Objects.isNull(file)) {
            return null;
        }
        String text = CommonUtil.getString(file);
        if (Objects.isNull(text)) {
            return null;
        }
        return JSON.parseObject(text, Article.class);
    }

    /**
     * 保存文件
     *
     * @param article
     */
    private void saveFile(Article article) {
        String content = JSON.toJSONString(article);
        CommonUtil.writeStringByPrintWriter(article.getId(), content, dbProperties.getArticle());
    }

    private HttpResponse deleteFile(String id) {
        String path = dbProperties.getArticle();
        File[] files = CommonUtil.getDirFiles(path);
        if (Objects.isNull(files)) {
            return HttpResponseUtil.fail("文章列表为空！", null);
        }
        for (File file : files) {
            if (file.getName().equals(id)) {
                file.delete();
                return HttpResponseUtil.success("删除文章成功！", null);
            }
        }
        localCache.delete(CacheKey.LOCAL_ARTICLE_LIST);

        return HttpResponseUtil.fail("想要删除的文章不存在！", null);

    }


}
